import React, { useState, useEffect } from 'react';
import { Form, Input, Select, DatePicker, Button, Space, InputNumber, Modal, Table, message, } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { orderList, orderDetail, orderEdit } from "../../api/account";
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);



export default function Order() {
    const { RangePicker } = DatePicker;
    const [queryData, setQueryData] = useState({});
    const [pagination, setPagination] = useState({ current: 1, pageSize: 5 });
    const [form] = Form.useForm();
    const [orders, setOrders] = useState([]);
    const [checkRecord, setCheckRecord] = useState({});
    const [editRecord, setEditRecord] = useState(null);
    const [editForm] = Form.useForm();

    const columns = [
        {
            title: '订单号',
            dataIndex: 'orderNo',
            key: 'orderNo',

        },
        {
            title: '下单时间',
            dataIndex: 'orderTime',
            key: 'orderTime',
        },
        {
            title: '联系电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '收货人',
            key: 'consignee',
            dataIndex: 'consignee',
        },
        {
            title: '送货地址',
            dataIndex: 'deliverAddress',
            key: 'deliverAddress',
        },
        {
            title: '送达时间',
            dataIndex: 'deliveryTime',
            key: 'deliveryTime',
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
        },
        {
            title: '订单金额',
            key: 'orderAmount',
            dataIndex: 'orderAmount',
        },
        {
            title: '订单状态',
            dataIndex: 'orderState',
            key: 'orderState',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => handleCheck(record)}>查看</a>
                    <a onClick={() => handleEdit(record)}>编辑</a>
                </Space>
            ),
        },
    ];

    const fetchOrder = async (currentPage, pageSize, queryParams = {}) => {
        const res = await orderList({
            currentPage,
            pageSize,
            ...queryParams,
        });

        setOrders(res.data.data);

        setPagination((prevPagination) => ({
            ...prevPagination,
            total: res.data.total,
        }));
    };


    const data = orders.map((item) => {

        const orderTime = new Date(item.orderTime);
        const Y = orderTime.getFullYear();
        const M = (orderTime.getMonth() + 1).toString().padStart(2, '0');
        const D = orderTime.getDate().toString().padStart(2, '0');
        const H = orderTime.getHours().toString().padStart(2, '0');
        const m = orderTime.getMinutes().toString().padStart(2, '0');
        const S = orderTime.getSeconds().toString().padStart(2, '0');

        const deliveryTime = new Date(item.deliveryTime);
        const Y1 = deliveryTime.getFullYear();
        const M1 = (deliveryTime.getMonth() + 1).toString().padStart(2, '0');
        const D1 = deliveryTime.getDate().toString().padStart(2, '0');
        const H1 = deliveryTime.getHours().toString().padStart(2, '0');
        const m1 = deliveryTime.getMinutes().toString().padStart(2, '0');
        const S1 = deliveryTime.getSeconds().toString().padStart(2, '0');

        return {
            orderNo: item.orderNo,
            orderTime: `${Y}-${M}-${D}-${H}:${m}:${S}`,
            phone: item.phone,
            consignee: item.consignee,
            deliverAddress: item.deliverAddress,
            deliveryTime: `${Y1}-${M1}-${D1}-${H1}:${m1}:${S1}`,
            remarks: item.remarks,
            orderAmount: item.orderAmount,
            orderState: item.orderState,
            id: item.id,
        };
    });

    useEffect(() => {
        fetchOrder(pagination.current, pagination.pageSize, queryData);
    }, [pagination.current, pagination.pageSize, queryData]);

    const handleTableChange = (newPagination) => {
        setPagination({
            ...pagination,
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        });
    };


    const onFinish = (values) => {
        const newQueryData = { ...queryData, ...values };

        setPagination((prevPagination) => ({
            ...prevPagination,
            current: 1,
        }));

        if (values.orderNo !== undefined) {
            newQueryData.orderNo = values.orderNo;
        }
        if (values.consignee !== undefined) {
            newQueryData.consignee = values.consignee;
        }
        if (values.phone !== undefined) {
            newQueryData.phone = values.phone;
        }
        if (values.orderState !== undefined) {
            newQueryData.orderState = values.orderState;
        }

        if (values.date && values.date.length === 2) {
            const dateRange = [
                values.date[0].format("YYYY-MM-DD"),
                values.date[1].format("YYYY-MM-DD"),
            ];

            newQueryData.date = JSON.stringify(dateRange);
        }
        setQueryData(newQueryData);
    };

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);

    const fetchOrderDetail = async (id) => {
        await orderDetail({ id });
    };

    const handleCheck = (record) => {
        fetchOrderDetail(record.id)
        setCheckRecord(record)
        showModal();
    };

    const showModal = () => {
        setIsModalOpen(true);
    };
    const showEditModal = () => {
        setIsEditModalOpen(true)
    }
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
        setIsEditModalOpen(false)
    };

    const handleEdit = (record) => {
        setEditRecord(record);
        editForm.setFieldsValue({
            orderNo: record.orderNo,
            consignee: record.consignee,
            deliverAddress: record.deliverAddress,
            orderAmount: record.orderAmount,
            remarks: record.remarks,
            phone: record.phone,
            deliveryTime: record.deliveryTime,
            orderTime: record.orderTime,
            orderState: record.orderState,
        });
        showEditModal();
    };


    const handleEditSubmit = async () => {
        const values = await editForm.validateFields();
        console.log(values);
        const updateData = {
            id: editRecord.id,
            orderNo: editRecord.orderNo,
            consignee: values.consignee,
            deliverAddress: values.deliverAddress,
            orderAmount: editRecord.orderAmount,
            remarks: values.remarks,
            phone: values.phone,
            orderTime: editRecord.orderTime,
            deliveryTime: values.deliveryTime,
            orderState: values.orderState,
        };
        let res = await orderEdit(updateData);
        console.log(res);
        if (res.data.code == 0) {
            setIsEditModalOpen(false);
            fetchOrder(pagination.current, pagination.pageSize, queryData);
            message.success(res.data.msg);
        } else {
            message.error(res.data.msg);
        }

    };

    const layout = {
        labelCol: {
            span: 4,
        },
    };
    return (
        <>
            <div className="app-content">
                <Form
                    form={form}
                    onFinish={onFinish}
                    style={{
                        width: '90%',
                        marginTop: 10,
                        display: 'flex',
                        flexWrap: 'wrap',
                        justifyContent: 'space-between'
                    }}>
                    <Form.Item
                        name="orderNo"
                        label="订单号"
                    >
                        <Input placeholder='请输入订单号' style={{
                            width: 200,
                        }} />

                    </Form.Item>
                    <Form.Item
                        name="consignee"
                        label="收货人"
                    >
                        <Input placeholder='请输入收货人' style={{
                            width: 200,
                        }} />

                    </Form.Item>
                    <Form.Item
                        name="phone"
                        label="手机号"
                    >
                        <InputNumber placeholder='请输入手机号' min={0} max={1999999999} style={{
                            width: 200,
                        }} />

                    </Form.Item>
                    <Form.Item
                        name="orderState"
                        label="订单状态"
                    >
                        <Select
                            placeholder="请选择订单状态"
                            allowClear
                            style={{
                                width: 200,
                            }}
                        >
                            <Select.Option value="已受理">已受理</Select.Option>
                            <Select.Option value="派送中">派送中</Select.Option>
                            <Select.Option value="已完成">已完成</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="date"
                        label="选择时间"
                    >
                        <RangePicker style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        name="id">
                        <Space style={{ width: 650 }}>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                搜索
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>


                <div>
                    <Table
                        columns={columns}
                        dataSource={data}
                        tableLayout='fixed'
                        style={{ width: '100%' }}
                        pagination={pagination}
                        onChange={handleTableChange}
                    />
                </div>
                <Modal title="详情查看" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <p><strong>订单号：</strong>{checkRecord.orderNo}</p>
                    <p><strong>收货人:</strong>{checkRecord.consignee}</p>
                    <p><strong>送货地址：</strong>{checkRecord.deliverAddress}</p>
                    <p><strong>订单金额：</strong>{checkRecord.orderAmount}</p>
                    <p><strong>订单备注：</strong>{checkRecord.remarks}</p>
                    <p><strong>联系电话：</strong>{checkRecord.phone}</p>
                    <p><strong>下单时间：</strong>{checkRecord.orderTime}</p>
                    <p><strong>送达时间：</strong>{checkRecord.deliveryTime}</p>
                    <p><strong>状态：</strong>{checkRecord.orderState}</p>
                </Modal>

                <Modal title="编辑" open={isEditModalOpen} onOk={handleEditSubmit} onCancel={handleCancel}>
                    <Form form={editForm} onFinish={handleEditSubmit} {...layout}>
                        <Form.Item label="订单号" name="orderNo">
                            <Input disabled />
                        </Form.Item>
                        <Form.Item label="收货人" name="consignee">
                            <Input />
                        </Form.Item>
                        <Form.Item label="送货地址" name="deliverAddress">
                            <Input />
                        </Form.Item>
                        <Form.Item label="订单金额" name="orderAmount">
                            <Input disabled />
                        </Form.Item>
                        <Form.Item label="订单备注" name="remarks">
                            <Input />
                        </Form.Item>
                        <Form.Item label="联系电话" name="phone">
                            <InputNumber style={{ width: '100%' }} min={13000000000} max={19999999999} />
                        </Form.Item>
                        <Form.Item label="下单时间" name="orderTime">
                            <Input disabled />
                        </Form.Item>
                        <Form.Item label="送达时间" name="deliveryTime">
                            <Input />
                        </Form.Item>
                        <Form.Item label="状态" name="orderState">
                            <Select>
                                <Select.Option value="已受理">已受理</Select.Option>
                                <Select.Option value="派送中">派送中</Select.Option>
                                <Select.Option value="已完成">已完成</Select.Option>
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        </>
    )
}
